﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using Prism.Mvvm;
using YF_Music.Core.Enums;

namespace YF_Music.Core.Models
{
  public class MusicItem : BindableBase
  {
    private string id;

    public string ID
    {
      get { return id; }
      set { SetProperty(ref id, value); }
    }

    /// <summary>
    /// 歌曲标题
    /// </summary>
    public string Title { get => _title; set => SetProperty(ref _title, value); }
    private string _title;

    /// <summary>
    /// 艺术家 / 演唱者
    /// </summary>
    public string Author { get => _author; set => SetProperty(ref _author, value); }
    private string _author;

    /// <summary>
    /// 专辑名称
    /// </summary>
    public string Album { get => _album; set => SetProperty(ref _album, value); }
    private string _album;

    /// <summary>
    /// 歌曲时长
    /// </summary>
    public TimeSpan Duration { get => _duration; set => SetProperty(ref _duration, value); }
    private TimeSpan _duration;

    /// <summary>
    /// 文件大小（单位：MB）
    /// </summary>
    public string FileSize { get => _fileSize; set => SetProperty(ref _fileSize, value); }
    private string _fileSize;

    /// <summary>
    /// 文件格式（如MP3/FLAC）
    /// </summary>
    public string Format { get => _format; set => SetProperty(ref _format, value); }
    private string _format;



    /// <summary>
    /// 播放次数
    /// </summary>
    public int PlayCount { get => _playCount; set => SetProperty(ref _playCount, value); }
    private int _playCount;

    /// <summary>
    /// 添加时间（文件创建时间）
    /// </summary>
    public DateTime AddTime { get => _addTime; set => SetProperty(ref _addTime, value); }
    private DateTime _addTime;

    /// <summary>
    /// 文件路径
    /// </summary>
    public string FilePath { get => _filePath; set => SetProperty(ref _filePath, value); }
    private string _filePath;

    /// <summary>
    /// 是否已下载
    /// </summary>
    public bool Downloaded { get => _downloaded; set => SetProperty(ref _downloaded, value); }
    private bool _downloaded;

    /// <summary>
    /// 专辑图像（ImageSource）
    /// </summary>
    public ImageSource AlbumArt { get => _albumArt; set => SetProperty(ref _albumArt, value); }
    public bool IsDefaultImage { get; set; } = false;

    private ImageSource _albumArt;
    private Enm_ToneQuality toneQuality;
    public Enm_ToneQuality SoundQuality
    {
      get => toneQuality;
      set
      {
        SetProperty(ref toneQuality, value);
      }
    }

    private string lyricPath;
    /// <summary>
    /// 歌词路径
    /// </summary>
    public string LyricPath
    {
      get { return lyricPath; }
      set { SetProperty(ref lyricPath, value); }
    }



    /// <summary>
    /// 从文件路径创建音乐模型（包含标签信息和专辑图像）
    /// </summary>
    public static MusicItem FromFile(string path)
    {
      var model = new MusicItem
      {
        FilePath = path,
        AddTime = File.GetCreationTime(path),
        Format = Path.GetExtension(path)?.TrimStart('.').ToUpper() ?? "UNKNOWN",
        Downloaded = File.Exists(path),
        PlayCount = 0 // 可从数据库读取
      };

      var fileInfo = new FileInfo(path);
      double sizeInMB = fileInfo.Length / 1024d / 1024d;
      model.FileSize = $"{sizeInMB:F2} MB";

      try
      {
        var file = TagLib.File.Create(path);

        model.Title = string.IsNullOrWhiteSpace(file.Tag.Title)
            ? Path.GetFileNameWithoutExtension(path)
            : file.Tag.Title;

        model.Author = file.Tag.FirstPerformer ?? "未知歌手";
        model.Album = file.Tag.Album ?? "未知专辑";
        model.Duration = file.Properties.Duration;

        int bitrate = file.Properties.AudioBitrate;
        model.SoundQuality = bitrate switch
        {
          >= 900 => Enm_ToneQuality.SQ,
          >= 256 => Enm_ToneQuality.HQ,
          _ => Enm_ToneQuality.SD,
        };

        // 读取封面图
        if (file.Tag.Pictures.Length > 0)
        {
          var picData = file.Tag.Pictures[0].Data.Data;
          model.AlbumArt = LoadImage(picData);
        }
        else
        {
          model.AlbumArt = LoadDefaultImage();
          model.IsDefaultImage = true;
        }
      }
      catch
      {
        model.Title = Path.GetFileNameWithoutExtension(path);
        model.Author = "未知";
        model.Album = "未知";
        model.Duration = TimeSpan.Zero;
        model.SoundQuality = Enm_ToneQuality.SD;
        model.AlbumArt = LoadDefaultImage();
      }
      model.ID = $"{model.Author}_{model.Title}";
      return model;
    }

    /// <summary>
    /// 将 byte[] 图片数据转换为 ImageSource
    /// </summary>
    private static ImageSource LoadImage(byte[] data)
    {
      using var ms = new MemoryStream(data);
      var img = new BitmapImage();
      img.BeginInit();
      img.CacheOption = BitmapCacheOption.OnLoad;
      img.StreamSource = ms;
      img.EndInit();
      img.Freeze();
      return img;
    }

    /// <summary>
    /// 加载默认封面图
    /// </summary>
    public static ImageSource LoadDefaultImage()
    {
      return new BitmapImage(new Uri("pack://application:,,,/YF_Music.Core;component/Images/default_album.png"));
    }

  }
}
